# fpdf2
from fpdf import FPDF

from pathlib import Path
import matplotlib.pyplot as plt
from datetime import datetime
import os
import pandas as pd
import time
import shutil
import requests

size_1 = "30"
# 二级标题
size_2 = "20"
size_3 = "18"
# 段落
size_p = "14"


class PDF(FPDF):
    def header(self):
        # 设置页眉字体
        self.set_font("Arial", "B", 12)
        image_width = 30  # 图片宽度
        image_height = 15  # 图片高度
        page_width = self.w - self.r_margin  # 页面宽度减去右边距
        x_position = page_width - image_width  # 计算右对齐的起始 X 坐标
        try:
            logpath = Path("./static") / "pdflogo.png"
            print(logpath, logpath.exists())
            if logpath.exists():
                self.image(logpath, x=x_position, y=3, w=image_width, h=image_height)
        except Exception as e:
            print(str(e))

        # 设置正文开始的 Y 坐标
        self.set_y(20)  # 页眉高度+间距


def set_br(n=1):
    return "<br>" * n


def get_filename():
    script_dir = os.path.dirname(os.path.abspath(__name__))

    date = time.strftime("%Y%m%d", time.localtime())
    path = script_dir + f"/static/upload/{date}"
    directory = Path(path)
    directory.mkdir(parents=True, exist_ok=True)
    return path


def init_pdf():
    script_dir = os.path.dirname(os.path.abspath(__name__))
    font_path = os.path.join(script_dir, "static", "simsun.ttc")
    pdf = PDF()
    pdf.add_font("SimSun", "", font_path, uni=True)  # 添加常规字体
    pdf.add_font("SimSun", "B", font_path, uni=True)  # 添加加粗字体
    pdf.add_font("SimSun", "I", font_path, uni=True)  # 添加加粗字体
    pdf.set_font("SimSun", size=12)
    return pdf


def draw_p1(pdf, page1):
    p1 = f"""
     {set_br(2)}
 <font size="{size_1}">
      <p align="center">{page1['title']}</p>
 </font>
    {set_br(8)}
 <font size="{size_p}">
     <p align="center"> {page1["times"][0]} - {page1["times"][1]}</p> 
</font>
<p></p>
{set_br(16)} 
<p></p>
    """
    pdf.write_html(p1)
    with pdf.table(width=100, col_widths=(40, 100), text_align="CENTER") as table1:
        row = table1.row()
        row.cell("项目名称")
        row.cell(page1["project_name"])

        row = table1.row()
        row.cell("报告编制")
        row.cell(page1["reporter"])

        row = table1.row()
        row.cell("报告审核")
        row.cell(page1["examine"])

        row = table1.row()
        row.cell("报告批准")
        row.cell(page1["permiss"])
    p2 = f"""
         {set_br(6)}
          <font size="16">
        <p align="center">{page1['support']}</p>
         </font>
         <br>
        <font size="16">
        <p align="center">{page1['create_time']}</p>
         </font>
    """
    pdf.write_html(p2)



def create_port_byperson(page1, page2, page3, page4, type_):
    fileName = "诊断报告"
    pdf = init_pdf()
    pdf.add_page()
    draw_p1(pdf, page1)
   
    date = time.strftime("%Y%m%d", time.localtime())
    script_dir = os.path.dirname(os.path.abspath(__name__))
    path = script_dir + f"/static/upload/{date}"
    if not os.path.exists(path):
        os.makedirs(path)
    time_end = time.strftime("%Y%m%d_%H%M%S", time.localtime())
    pdf_name = get_filename() + "/" + f"{fileName}_{time_end}.pdf"
    if type_ == 1:
        fileName = page3["device_name"] + fileName
        pdf_name = script_dir + f"/static/upload/" + f"{fileName}_{time_end}.pdf"
    pdf.output(pdf_name)
    return [pdf_name, f"{fileName}_{time_end}"]


def get_picture(data, number, width=10, height=3):
    if len(data) > 0:
        for item in data:
            item["timestamp"] = datetime.fromtimestamp(item["id"]).strftime(
                "%m-%d %H:%M:%S"
            )
        df = pd.DataFrame(data)
        plt.rcParams["font.sans-serif"] = ["SimHei"]  # 设置中文字体为 SimHei
        plt.rcParams["axes.unicode_minus"] = False
        plt.figure(figsize=(width, height))
        plt.plot(
            df["timestamp"],
            df["acc_rms"],
            label="加速度",
            marker=".",
            markersize=2,
            alpha=1,
            linewidth=0.8,
        )
        plt.plot(
            df["timestamp"],
            df["vel_rms"],
            label="速度",
            marker=".",
            markersize=2,
            alpha=0.8,
            linewidth=0.8,
        )
        plt.xlabel("时间")
        plt.ylabel("值")
        plt.legend(fontsize="large")
        xticks = get_corr_values(df["timestamp"], 5)
        plt.xticks(xticks)
        plt.tight_layout()
        chart_file = (
            get_filename()
            + f"/chart_png_{int(datetime.now().timestamp())}_{number}.png"
        )
        plt.savefig(chart_file)
        plt.close()
        return chart_file


def transform_data(data):
    return [
        {
            "id": int(item["id"]),
            "acc_rms": item["Z"]["acc_rms"],
            "vel_rms": item["Z"]["vel_rms"],
        }
        for item in data
    ]


def get_corr_values(a, b):
    if len(a) == 0 or b <= 1:
        return []
    # 计算等比例索引
    indices = [int(i * (len(a) - 1) / (b - 1)) for i in range(b)]
    # 获取对应索引位置的值
    corresponding_values = [a[idx] for idx in indices]
    return corresponding_values

